<template>
  <div class="my-courses">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>我的课程</h2>
          <el-input
            v-model="searchQuery"
            placeholder="搜索课程"
            class="search-input"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </template>

      <!-- 课程列表 -->
      <div class="course-list">
        <el-row :gutter="20">
          <el-col 
            v-for="course in courseList" 
            :key="course.id" 
            :xs="24" 
            :sm="12" 
            :md="8" 
            :lg="6"
          >
            <el-card 
              class="course-card" 
              :body-style="{ padding: '0px' }"
              shadow="hover"
            >
              <div class="course-image">
                <el-image :src="course.cover" fit="cover" />
                <div class="course-progress">
                  <el-progress 
                    :percentage="course.progress" 
                    :format="format"
                    :stroke-width="4"
                  />
                </div>
              </div>
              <div class="course-info">
                <h3 class="course-title">{{ course.title }}</h3>
                <p class="course-teacher">{{ course.teacher }}</p>
                <div class="course-meta">
                  <span class="course-level">
                    <el-tag size="small" :type="getLevelType(course.level)">
                      {{ course.level }}
                    </el-tag>
                  </span>
                  <span class="course-rating">
                    <el-rate
                      v-model="course.rating"
                      disabled
                      text-color="#ff9900"
                    />
                  </span>
                </div>
                <div class="course-actions">
                  <el-button type="danger" @click="cancelCourse(course.id)">
                    取消课程
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[8, 16, 24, 32]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 搜索
const searchQuery = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)

// 课程列表
const courseList = ref([])

// 获取课程列表
const fetchCourseList = async () => {
  try {
    // 优先从 localStorage 中读取数据
    const savedCourses = localStorage.getItem('myCourses');
    let mockData;
    
    if (savedCourses) {
      mockData = JSON.parse(savedCourses);
    } else {
      // 如果没有保存的数据，则使用模拟数据
      mockData = Array.from({ length: 20 }, (_, index) => ({
        id: index + 1,
        title: `课程${index + 1}`,
        teacher: `讲师${index + 1}`,
        cover: `https://picsum.photos/300/200?random=${index}`,
        level: ['初级', '中级', '高级'][index % 3],
        rating: Math.floor(Math.random() * 3) + 3,
        progress: Math.floor(Math.random() * 100)
      }));
      // 首次加载时保存到 localStorage
      localStorage.setItem('myCourses', JSON.stringify(mockData));
    }
    
    // 模拟搜索
    let filteredData = mockData;
    if (searchQuery.value) {
      filteredData = mockData.filter(course => 
        course.title.includes(searchQuery.value) ||
        course.teacher.includes(searchQuery.value)
      );
    }
    
    total.value = filteredData.length;
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    courseList.value = filteredData.slice(start, end);
  } catch (error) {
    console.error('获取课程列表失败:', error);
    ElMessage.error('获取课程列表失败');
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchCourseList()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchCourseList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchCourseList()
}

// 格式化进度
const format = (percentage) => {
  return percentage === 100 ? '已完成' : `${percentage}%`
}

// 获取难度等级标签类型
const getLevelType = (level) => {
  const types = {
    '初级': 'success',
    '中级': 'warning',
    '高级': 'danger'
  }
  return types[level] || 'info'
}

// 继续学习
const continueLearning = (course) => {
  router.push(`/course/learn/${course.id}`)
}

// 查看课程详情
const viewCourseDetail = (course) => {
  router.push(`/course/detail/${course.id}`)
}

// 取消课程
const cancelCourse = (courseId) => {
  // 查找并移除课程
  const index = courseList.value.findIndex(course => course.id === courseId);
  if (index !== -1) {
    courseList.value.splice(index, 1);
    total.value = courseList.value.length; // 更新总数
    // 将更新后的课程列表保存到 localStorage
    localStorage.setItem('myCourses', JSON.stringify(courseList.value));
    ElMessage.success('课程已取消');
  }
};

onMounted(() => {
  fetchCourseList()
})
</script>

<style scoped>
.my-courses {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
}

.search-input {
  width: 300px;
}

.course-list {
  margin-top: 20px;
}

.course-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.course-card:hover {
  transform: translateY(-5px);
}

.course-image {
  position: relative;
  height: 200px;
}

.course-image .el-image {
  width: 100%;
  height: 100%;
}

.course-progress {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px;
  background: rgba(0, 0, 0, 0.5);
}

.course-info {
  padding: 15px;
}

.course-title {
  margin: 0 0 10px;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.course-teacher {
  margin: 0 0 10px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.course-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.course-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 